<template>
  <div class="shopping-container">
    <div class="shopping-cover-container">
      <van-swipe :autoplay="3000">
        <van-swipe-item v-for="(image, index) in coverList" :key="index">
          <img v-lazy="imgUrl + image" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="shopping-info">
      <div class="name">{{ details.title }}</div>
      <div class="footer">
        <div class="price">{{ type === 'integral' ? '积分' : '$' }} 
          <span class="num">
            {{ details.price }}
          </span>
        </div>
        <div class="price1" v-if="type !== 'integral'">$ {{ details.price1 }}</div>
        <div class="num">销量：{{ details.sold + details.soldinit }}件</div>
      </div>
    </div>
    <!-- 拼团容器 -->
    <div class="figview-container" v-if="type === 'figview'">
      <div class="title">
        {{ figviewCount }}人在拼团，可直接参与
        <span
          v-if="figviewList.length > 2"
          @click="figviewListShow = true"
        >
          查看全部
          <span class="iconfont icongengduo"></span>
        </span>
      </div>
      <div class="figview-item" v-for="(item, index) in figviewList" :key="index" v-if="index <= 1">
        <van-divider />
        <div class="figview-item-content">
          <div class="avatar">
            <img
              :src="imgUrl + item.avatar"
              alt
            />
          </div>
          <div class="name">{{ item.nickname }}</div>
          <div class="main">
            <div class="top">
              还差
              <span class="num">{{ item.remaining }}人</span>拼成
            </div>
            <div class="bottom" v-if="figviewListTimeIsShow">剩余{{item.time}}</div>
          </div>
          <div class="btn" @click="goFigview(item)">去拼单</div>
        </div>
      </div>
    </div>
    <div class="main-tab">
      <div class="tab-item" :class="tabIndex === 1 && 'active'" @click="tabIndex = 1">
        <span>商品详情</span>
      </div>
      <div class="tab-item" :class="tabIndex === 2 && 'active'" @click="tabIndex = 2">
        <span>评论详情</span>
      </div>
    </div>
    <div class="details-container" v-if="tabIndex === 1">
      <div v-html="details.content"></div>
    </div>
    <div class="evaluate-container" v-else>
      <div v-if="evaluateList.length">
        <div class="evaluate-item" v-for="(items, indexs) in evaluateList" :key="indexs">
          <div class="main">
            <div class="avatar">
              <img :src="imgUrl + items.headimgurl" alt />
            </div>
            <div class="middle">
              <div class="name">{{ items.nickname }}</div>
              <div class="content">{{ items.remark }}</div>
            </div>
            <div class="date">{{ items.addtime }}</div>
          </div>
          <div class="img-container" v-if="items.photos.length">
            <div class="img-item" v-for="(item, index) in items.photos" :key="index">
              <img :src="imgUrl + item" alt @click="viewImg(items.photos, index)" />
            </div>
          </div>
        </div>
      </div>
      <van-empty description="该商品暂无评论" v-else/>
    </div>

    <!-- 底部操作栏 -->
    <van-goods-action v-if="type !== 'figview' && type !== 'integral'">
      <van-goods-action-icon icon="chat-o" text="客服" @click="customerServiceClick" />
      <van-goods-action-icon
        icon="star"
        text="已收藏"
        color="#ff5000"
        v-if="isfav"
        @click="facClick(false)"
      />
      <van-goods-action-icon icon="star" text="收藏" color="#646566" v-else @click="facClick(true)" />
      <van-goods-action-button type="warning" text="加入购物车" @click="show = true" />
      <van-goods-action-button type="danger" text="立即购买" @click="show = true" />
    </van-goods-action>
    <!-- 底部操作栏 -->
    <van-goods-action v-else-if="type === 'integral'">
      <van-goods-action-icon icon="chat-o" text="客服" @click="customerServiceClick" />
      <van-goods-action-icon
        icon="star"
        text="已收藏"
        color="#ff5000"
        v-if="isfav"
        @click="facClick(false)"
      />
      <van-goods-action-icon icon="star" text="收藏" color="#646566" v-else @click="facClick(true)" />
      <van-goods-action-button
        type="danger"
        class="figview-btn"
        text="立即兑换"
        @click="integralShow = true; figviewId = null"
      />
    </van-goods-action>
    <!-- 底部操作栏 -->
    <van-goods-action v-else>
      <van-goods-action-icon icon="chat-o" text="客服" @click="customerServiceClick" />
      <van-goods-action-icon
        icon="star"
        text="已收藏"
        color="#ff5000"
        v-if="isfav"
        @click="facClick(false)"
      />
      <van-goods-action-icon icon="star" text="收藏" color="#646566" v-else @click="facClick(true)" />
      <van-goods-action-button
        type="danger"
        class="figview-btn"
        text="发起拼团"
        @click="figviewShow = true; figviewId = null"
      />
    </van-goods-action>

    <!-- 商品规格 -->
    <van-sku
      v-model="show"
      @sku-selected="skuSelected"
      :sku="sku"
      :goods="goodDetails"
      :goods-id="goodDetails.id"
      :hide-stock="goodDetails.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    >
      <div slot="sku-header-price" style="color:#ee0a24" class="van-sku__goods-price">
        <span class="van-sku__price-symbol">$ </span>
        <span class="van-sku__price-num">{{ sku.price }}</span>
      </div>
    </van-sku>

    <!-- 商品规格,拼团商品 -->
    <van-sku
      v-model="figviewShow"
      :sku="sku"
      @sku-selected="skuSelected"
      :goods="goodDetails"
      :goods-id="goodDetails.id"
      :hide-stock="goodDetails.hide_stock"
      @buy-clicked="onFigviewClicked"
      :show-add-cart-btn="false"
      :buy-text="figviewId ? '加入拼团' : '发起拼团'"
    >
      <div slot="sku-header-price" style="color:#ee0a24" class="van-sku__goods-price">
        <span class="van-sku__price-symbol">$ </span>
        <span class="van-sku__price-num">{{ sku.price }}</span>
      </div>
    </van-sku>
    <!-- 商品规格,积分商品 -->
    <van-sku
      v-model="integralShow"
      :sku="sku"
      @sku-selected="skuSelected"
      :goods="goodDetails"
      :goods-id="goodDetails.id"
      :hide-stock="goodDetails.hide_stock"
      @buy-clicked="onIntegralClicked"
      :show-add-cart-btn="false"
      buy-text="立即兑换"
    >
      <div slot="sku-header-price" style="color:#ee0a24" class="van-sku__goods-price">
        <span class="van-sku__price-symbol">积分：</span>
        <span class="van-sku__price-num">{{ details.price }}</span>
      </div>
    </van-sku>

    <!-- 拼团列表弹窗 -->
    <van-popup
      v-model="figviewListShow"
      round
      position="bottom"
      closeable
    >
      <div class="figview-popup-title">可参与的拼团</div>
      <div class="figview-popup-container">
        <div class="figview-item" v-for="(item, index) in figviewList" :key="index">
          <div class="figview-item-content">
            <div class="avatar">
              <img
                :src="imgUrl + item.avatar"
                alt
              />
            </div>
            <div class="name">{{ item.nickname }}</div>
            <div class="main">
              <div class="top">
                还差
                <span class="num">{{ item.remaining }}人</span>拼成
              </div>
              <div class="bottom" v-if="figviewListTimeIsShow">剩余{{item.time}}</div>
            </div>
            <div class="btn" @click="goFigview(item)">去拼单</div>
          </div>
          <van-divider />
        </div>
      </div>
    </van-popup>

    <customerService ref="customerService" />
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import { Cache } from "@utils";
import customerService from "@components/customerService";
import moment from "moment";

export default {
  components: {
    customerService
  },
  data() {
    return {
      show: false,
      figviewShow: false,
      integralShow: false,
      isfav: false, // 是否收藏
      tabIndex: 1,
      coverList: [],
      details: {},
      evaluateList: [],
      goodDetails: {
        picture: null
      },
      sku: {
        // // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [],
        // // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [],
        price: null, // 默认价格（单位元）
        stock_num: 0, // 商品总库存
        collection_id: null, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        // none_sku: true, // 是否无规格商品
        hide_stock: false // 是否隐藏剩余库存
      },
      figviewList: [], // 拼团列表
      figviewTimer: null, // 拼团列表倒计时
      figviewListTimeIsShow: false,
      figviewId: null, // 拼团Id
      figviewListShow: false
    };
  },
  computed: {
    imgUrl() {
      return this.$imgUrl;
    },
    userInfo() {
      return this.$store.state.userData;
    },
    type() {
      return this.$route.query.type;
    },
    figviewCount() {
      let num = 0;
      this.figviewList.forEach(item => {
        num += item.num;
      });
      return num;
    }
  },
  created() {
    this.getDetails();
  },
  beforeDestroy() {
    clearInterval(this.figviewListTimeIsShow);
  },
  methods: {
    skuSelected (skuValue, selectedSku, selectedSkuComb) {
      this.sku.price = skuValue.selectedSkuComb.price / 100
    },
    goFigview(item) {
      this.figviewId = item.id;
      this.figviewShow = true;
    },
    formatSeconds(value) {
      var theTime = parseInt(value); // 秒
      var middle = 0; // 分
      var hour = 0; // 小时
      if (theTime > 60) {
        middle = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (middle > 60) {
          hour = parseInt(middle / 60);
          middle = parseInt(middle % 60);
        }
      }
      var result = "" + parseInt(theTime) + "";
      if (middle > 0) {
        result = "" + parseInt(middle) + ":" + result;
      }
      if (hour > 0) {
        result = "" + parseInt(hour) + ":" + result;
      }
      return result;
    },
    customerServiceClick() {
      this.$refs["customerService"].open();
    },
    onFigviewClicked(item) {
      if (!this.userInfo) {
        this.$dialog
          .alert({
            title: "温馨提示",
            message: "请先登录"
          })
          .then(() => {
            // on close
          });
        return;
      }
      if (this.figviewId) {
        Cache.set("buyShoppingData", [
          {
            name: this.details.title,
            price: this.details.price,
            people: this.details.people,
            picture: this.goodDetails.picture,
            num: item.selectedNum,
            id: this.details.id,
            figviewId: this.figviewId
          }
        ]);
        this.$router.push({
          path: "/payOrder",
          query: {
            type: "figviewJoin",
            isType: this.type
          }
        });
      } else {
        Cache.set("buyShoppingData", [
          {
            name: this.details.title,
            price: this.details.price,
            people: this.details.people,
            picture: this.goodDetails.picture,
            num: item.selectedNum,
            id: this.details.id
          }
        ]);
        this.$router.push({
          path: "/payOrder",
          query: {
            type: "figview",
            isType: this.type
          }
        });
      }
    },
    onIntegralClicked (item) {
      if (!this.userInfo) {
        this.$dialog
          .alert({
            title: "温馨提示",
            message: "请先登录"
          })
          .then(() => {
            // on close
          });
        return;
      }
      Cache.set("buyShoppingData", [
          {
            name: this.details.title,
            price: this.details.price,
            picture: this.goodDetails.picture,
            num: item.selectedNum,
            id: this.details.id
          }
        ]);
        this.$router.push({
          path: "/payOrder",
          query: {
            type: "integral",
            isType: this.type
          }
        });
      console.log(item)
    },
    /*
     *@name: 收藏
     *@param:{type}
     *@description:
     *@return:
     *@author: lupan
     *@date: 2020-05-16 13:58:45
     */
    async facClick(or) {
      const result = await this.$fetchPost("/home/member/fav", {
        tid: this.details.id
      });
      if (!result.success) {
        this.$toast(result.msg);
        return;
      }
      this.isfav = or;
    },
    /*
     *@name: 获取商品详情
     *@param:{type}
     *@description:
     *@return:
     *@author: lupan
     *@date: 2020-05-07 21:35:11
     */
    async getDetails() {
      const obj = {
        integral: '/home/item/inteview',
        new: "/home/item/view", // 新品上架（商品详情页）
        actview: "/home/item/actview", // 限时抢购（商品详情页）
        figview: "/home/item/figview" // 国际拼团（商品详情页）
      };
      const result = await this.$fetchGet(obj[this.$route.query.type], {
        id: this.$route.query.id
      });
      if (!result.success) {
        this.$toast(result.msg);
        return;
      }
      this.details = result.data.db;
      this.evaluateList = result.data.commentlist.map(item => {
        item.photos = JSON.parse(item.photos)
        return item
      })
      if (result.data.speclist.length) {
        this.sku.stock_num = result.data.db.stocks;
        this.sku.tree = result.data.speclist.map(items => {
          return {
            k: items.name, // skuKeyName：规格类目名称
            k_s: 's' + items.id, // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: items.values.map(item => {
              return {
                id: item.id, // skuValueId：规格值 id
                name: item.name // skuValueName：规格值名称
              }
            })
          }
        })
        let arr = result.data.speclist.map(items => {
          return items.values.map(item => {
            return {
              id: item.id, // skuId
              ['s' + items.id]: item.id, // 规格类目 k_s 为 s1 的对应规格值 id
              price: item.price * 100, // 价格（单位分）
              stock_num: +item.stock // 当前 sku 组合对应的库存
            }
          })
        })
        this.sku.list = arr.flat(2)
      } else {
        this.sku.stock_num = result.data.db.stock;
        this.sku.tree = [{
          k: '统一规格', // skuKeyName：规格类目名称
          k_s: '默认规格', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
          v: [{
            id: result.data.db.id, // skuValueId：规格值 id
            name: '默认规格' // skuValueName：规格值名称
          }]
        }]
        this.sku.list = [{
          id: result.data.db.id, // skuId
          '默认规格': result.data.db.id, // 规格类目 k_s 为 s1 的对应规格值 id
          price: result.data.db.price * 100, // 价格（单位分）
          stock_num: result.data.db.stock // 当前 sku 组合对应的库存
        }]
      }
      this.sku.price = this.details.price;
      this.coverList = result.data.imglist;
      this.goodDetails.picture = this.imgUrl + this.details.indexpic;
      this.isfav = result.data.fav === 1;
      if (result.data.res) {
        this.figviewList = result.data.res;
        if (this.figviewList.length) {
          this.figviewList.map(item => {
            this.figviewListTimeIsShow = true;
            item.time = this.formatSeconds(
              item.expire_time - parseInt(moment().valueOf() / 1000)
            );
          });
          this.figviewTimer = setInterval(() => {
            this.figviewList.map(item => {
              this.figviewListTimeIsShow = false;
              item.time = this.formatSeconds(
                item.expire_time - parseInt(moment().valueOf() / 1000)
              );
              this.$nextTick(() => {
                this.figviewListTimeIsShow = true;
              });
            });
          }, 1000);
        }
      }
    },
    viewImg(imgList, index) {
      ImagePreview({
        images: imgList.map(item => this.imgUrl + item),
        startPosition: index
      });
    },
    onBuyClicked(item) {
      if (!this.userInfo) {
        this.$dialog
          .alert({
            title: "温馨提示",
            message: "请先登录"
          })
          .then(() => {
            // on close
          });
        return;
      }
      console.log(item)
      Cache.set("buyShoppingData", [
        {
          name: this.details.title,
          price: this.details.price,
          picture: this.goodDetails.picture,
          num: item.selectedNum,
          id: this.details.id,
          specification: item.selectedSkuComb['默认规格'] ? null : item.selectedSkuComb.id,
          specnames: item.selectedSkuComb['默认规格'] ? null : this.sku.tree[0].v.filter(i => i.id === item.selectedSkuComb.id)[0].name
        }
      ]);
      this.$router.push({
        path: "/payOrder",
        query: {
          type: "good",
          isType: this.type
        }
      });
    },
    async onAddCartClicked(item) {
      if (!this.userInfo) {
        this.$dialog
          .alert({
            title: "温馨提示",
            message: "请先登录"
          })
          .then(() => {
            // on close
          });
        return;
      }
      let params = {
        productid: this.details.id,
        num: item.selectedNum
      }
      if (!item.selectedSkuComb['默认规格']) {
        params.specification = item.selectedSkuComb.id
      }
      const result = await this.$fetchGet("/home/cart/add", params);
      if (!result.success) {
        this.$toast(result.msg);
        return;
      }
      this.show = false;
      this.$store.commit("changeCartList");
      this.$toast("加入购物车成功");
    }
  }
};
</script>

<style lang="scss">
.shopping-container {
  width: 100vw;
  height: calc(100vh - 200px);
  overflow-y: auto;
  .shopping-cover-container {
    // width: 90vw;
    margin: 30px;
    border-radius: 50px;
    img {
      width: calc(100vw - 60px);
    }
  }
  .shopping-info {
    padding: 20px;
    background: #ffffff;
    box-shadow: 0 0px 5px #888;
    .name {
      font-size: 30px;
      font-weight: 500;
      line-height: 50px;
      margin-bottom: 20pxa;
    }
    .footer {
      display: flex;
      font-size: 25px;
      line-height: 50px;
      font-weight: 600;
      // & > div {
      //   flex: 1;
      // }
      .price {
        font-size: 30px;
        color: #ff3b3b;
        .num {
          font-size: 45px;
          color: #ff3b3b;
          margin-left: -8px;
        }
      }
      .price1 {
        margin-left: 20px;
        font-size: 20px;
        color: #dddddd;
        line-height: 60px;
        text-decoration: line-through;
      }
      .num {
        flex: 1;
        text-align: right;
        color: #929292;
      }
    }
  }
  .figview-container {
    margin-top: 50px;
    padding: 20px;
    background: #ffffff;
    box-shadow: 0 5px 10px #888;
    .title {
      font-size: 25px;
      line-height: 40px;
      color: #353535;
      span {
        float: right;
        color: #a0a0a0;
      }
    }
    .figview-item {
      .figview-item-content {
        display: flex;
        line-height: 100px;
        .avatar {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          overflow: hidden;
        }
        .name {
          font-size: 25px;
          margin-left: 20px;
        }
        .main {
          margin-top: 20px;
          flex: 1;
          text-align: right;
          line-height: 30px;
          color: #1a1a1a;
          .top {
            font-size: 20px;
            .num {
              color: #de4e4d;
            }
          }
        }
        .btn {
          background: #fe392a;
          border-radius: 15px;
          color: #fff;
          line-height: 60px;
          text-align: center;
          width: 100px;
          height: 60px;
          margin-top: 20px;
          margin-left: 20px;
        }
      }
    }
  }
  .figview-popup-title {
    position: absolute;
    width: 100%;
    text-align: center;
    line-height: 50px;
    font-size: 25px;
    background: #fff;
  }
  .figview-popup-container {
    padding: 50px 20px;
    max-height: 70vh;
    overflow-y: auto;
    .figview-item {
      .figview-item-content {
        display: flex;
        line-height: 100px;
        .avatar {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          overflow: hidden;
        }
        .name {
          font-size: 25px;
          margin-left: 20px;
        }
        .main {
          margin-top: 20px;
          flex: 1;
          text-align: right;
          line-height: 30px;
          color: #1a1a1a;
          .top {
            font-size: 20px;
            .num {
              color: #de4e4d;
            }
          }
        }
        .btn {
          background: #fe392a;
          border-radius: 15px;
          color: #fff;
          line-height: 60px;
          text-align: center;
          width: 100px;
          height: 60px;
          margin-top: 20px;
          margin-left: 20px;
        }
      }
    }
  }
  .main-tab {
    margin-top: 30px;
    background: #ffffff;
    display: flex;
    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 30px;
      font-weight: 500;
      color: #1b1b1b;
      line-height: 100px;
      border-bottom: 1px solid #ededed;
      &.active {
        color: #000000;
        span {
          line-height: 100px;
          display: inline-block;
          border-bottom: 5px solid #fa4d38;
        }
      }
    }
  }
  .details-container {
    width: 100vw;
    overflow: hidden;
    word-break:break-all;
  }
  .evaluate-container {
    background: #ffffff;
    .evaluate-item {
      padding: 20px;
      border-bottom: 1px solid #e8e8e8;
      .main {
        display: flex;
        position: relative;
        .avatar {
          border-radius: 50%;
          overflow: hidden;
          img {
            width: 100px;
            height: 100px;
          }
        }
        .middle {
          flex: 1;
          margin: 0 20px;
          padding-top: 10px;
          .name {
            font-size: 30px;
            font-weight: 600;
            margin-bottom: 10px;
          }
          .content {
            font-size: 25px;
            font-weight: 600;
            color: #969696;
          }
        }
        .date {
          position: absolute;
          right: 0;
          top: 10px;
          font-size: 25px;
          color: #dbdbdb;
        }
      }
      .img-container {
        display: flex;
        .img-item {
          flex: 1;
          margin: 20px;
          text-align: center;
          img {
            height: 150px;
          }
        }
      }
    }
  }
  .van-goods-action {
    height: 100px;
    line-height: 100px;
    box-shadow: 0 -1px 10px #888;
    .van-goods-action-icon {
      min-width: 100px;
      font-size: 25px;
      &__icon {
        font-size: 35px;
      }
    }
    .van-goods-action-button--first {
      border-top-left-radius: 30px;
      border-bottom-left-radius: 30px;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      height: 70px;
    }
    .van-goods-action-button--last {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      border-top-right-radius: 30px;
      border-bottom-right-radius: 30px;
      height: 70px;
    }
    .figview-btn {
      border-top-left-radius: 30px;
      border-bottom-left-radius: 30px;
      border-top-right-radius: 30px;
      border-bottom-right-radius: 30px;
      height: 70px;
    }
  }
}
</style>